﻿using Approval.API.Applcation.Command.PurchaseRelationCommand;
using Approval.Domain;
using Approval.Infrastructure.Impl;
using Approval.Infrastructure.Interface;
using MediatR;

namespace Approval.API.Applcation.CommandHandler.PurchaseRelationCommandHandler
{
    public class PurchaseRelationCreateCommandHandler : IRequestHandler<PurchaseRelationCreateCommand, int>
    {
        private readonly IPurchaseRelationRepository purchaseRelationRepository;

        public PurchaseRelationCreateCommandHandler(IPurchaseRelationRepository purchaseRelationRepository)
        {
            this.purchaseRelationRepository = purchaseRelationRepository;
        }

        public async Task<int> Handle(PurchaseRelationCreateCommand request, CancellationToken cancellationToken)
        {
            var list = await purchaseRelationRepository.GetInfo(x => x.PId == request.PId && x.ApprovalState == 3);
            if (list != null)
            {
                await purchaseRelationRepository.Delete(list.Id);
            }
            //默认第一次提交付款审批是彭于晏
            var hctRelation = new PurchaseRelation()
            {
                PId = request.PId,
                ApprovalId = request.ApprovalId != 0 ? request.ApprovalId : 4,
                ApprovalName = (request.ApprovalName == "") ? request.ApprovalName : "彭于晏",
                ApprovalDesc = null
            };
            var res = await purchaseRelationRepository.Create(hctRelation);
            return res;
        }
    }
}
